package com.jsh.erp.exception;

import com.jsh.erp.constants.ExceptionConstants;
import com.jsh.erp.controller.UnitController;
import com.jsh.erp.web.vo.BaseResponseInfo;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(UnitController.class);

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public BaseResponseInfo handleException(Exception e, HttpServletRequest request, HttpServletResponse response) {

        BaseResponseInfo responseInfo = new BaseResponseInfo(ExceptionConstants.SERVICE_SYSTEM_ERROR_CODE, ExceptionConstants.SERVICE_SYSTEM_ERROR_MSG, ExceptionConstants.SERVICE_SYSTEM_ERROR_MSG);

        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        // 针对业务参数异常的处理
        if (e instanceof BusinessParamCheckingException) {
            BusinessParamCheckingException be = (BusinessParamCheckingException) e;
            responseInfo.setCode(be.getCode());
            responseInfo.setData(be.getData());
            responseInfo.setMessage(be.getMessage());
        }

        //针对业务运行时异常的处理
        if (e instanceof BusinessRunTimeException) {
            BusinessRunTimeException be = (BusinessRunTimeException) e;
            responseInfo.setCode(be.getCode());
            responseInfo.setData(be.getData());
            responseInfo.setMessage(be.getMessage());
        }

        logger.error("Global Exception => url : {}", request.getRequestURL(), e);
        return responseInfo;
    }
}